<template>
  <el-drawer
    v-model="visible"
    :with-header="false"
    size="50%"
    direction="rtl"
    :close-on-click-modal="true"
    :show-close="true"
    class="issue-drawer"
  >
    <div class="drawer-header">
      <span class="drawer-title-bar"></span>
      <span class="drawer-title">问题反馈</span>
      <el-icon class="drawer-close" @click="close"><Close /></el-icon>
    </div>
    <el-tabs v-model="page" class="drawer-tabs" @tab-click="handleTabClick">
      <el-tab-pane label="提交新问题" name="form"></el-tab-pane>
      <el-tab-pane label="问题清单" name="list"></el-tab-pane>
    </el-tabs>
    <template v-if="page === 'list'">
      <div class="issue-list-section">
        <el-table
          :data="filteredIssues"
          style="width: 100%"
          size="small"
          v-if="filteredIssues.length"
          row-key="title"
        >
          <el-table-column type="expand" fixed="left">
            <template #default="scope">
              <div style="padding: 8px 24px 8px 8px">
                <div
                  style="font-weight: bold; font-size: 15px; margin-bottom: 6px"
                >
                  {{ scope.row.title }}
                </div>
                <div v-html="scope.row.content"></div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="title"
            label="标题"
            min-width="120"
            fixed="left"
          />
          <el-table-column prop="priority" label="优先级" width="80">
            <template #default="scope">
              <el-tag :type="priorityTagType(scope.row.priority)">{{
                priorityMap[scope.row.priority] || scope.row.priority
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.type === 'needs' ? 'success' : 'info'">{{
                typeMap[scope.row.type] || scope.row.type
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="expectTime" label="期望解决时间" width="140" />
          <el-table-column prop="createTime" label="创建时间" width="140" />
          <el-table-column
            prop="status"
            label="状态"
            width="120"
            :filters="statusFilters"
            :filter-method="filterStatus"
            filter-placement="bottom-end"
          >
            <template #default="scope">
              <template v-if="isAdmin && editingStatusRow === scope.$index">
                <el-select
                  v-model="scope.row.status"
                  size="small"
                  style="width: 100px"
                  @change="() => endEditStatus(scope.row)"
                  @blur="() => endEditStatus(scope.row)"
                  filterable
                  autofocus
                >
                  <el-option
                    v-for="item in statusFilters"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value"
                  />
                </el-select>
              </template>
              <template v-else>
                <el-tag
                  :type="statusTagType(scope.row.status)"
                  @click="isAdmin ? startEditStatus(scope.$index) : null"
                  style="cursor: pointer"
                >
                  {{ statusMap[scope.row.status] || scope.row.status }}
                </el-tag>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-else description="暂无问题" />
      </div>
    </template>
    <template v-else>
      <div class="issue-form-scroll">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="auto">
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="form.title"
              placeholder="请输入问题标题"
              maxlength="60"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="form.priority" placeholder="请选择优先级">
              <el-option label="低" value="low" />
              <el-option label="中" value="middle" />
              <el-option label="高" value="high" />
            </el-select>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择类型">
              <el-option label="问题" value="bug" />
              <el-option label="需求" value="needs" />
            </el-select>
          </el-form-item>
          <el-form-item label="期望解决时间" prop="expectTime">
            <el-date-picker
              v-model="form.expectTime"
              value-format="YYYY-MM-DD"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="详细内容" prop="content">
            <div class="editor-wrapper">
              <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" />
              <Editor
                v-model="form.content"
                :defaultConfig="editorConfig"
                mode="default"
                style="min-height: 180px; border-radius: 4px"
                @onCreated="handleEditorCreated"
                @customPaste="handleCustomPaste"
              />
            </div>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <div class="drawer-footer-bar">
      <el-button v-if="page === 'form'" type="primary" @click="handleSubmit">提交</el-button>
      <el-button v-if="page === 'form'" @click="resetForm">重置</el-button>
      <el-button @click="close">取消</el-button>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { ElMessage } from "element-plus";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import {
  fetchFeedbackList,
  createFeedback,
  updateFeedback,
} from "@/api/feedback";
import { Close } from '@element-plus/icons-vue'

const visible = ref(false);
const page = ref("form");
const isAdmin = true; // 可根据实际登录用户权限控制
const statusFilters = [
  { text: "待处理", value: "pending" },
  { text: "已解决", value: "fixed" },
  { text: "作废", value: "expired" },
];
const issues = ref([]);
const editingStatusRow = ref(null);

const filteredIssues = computed(() => issues.value);

const formRef = ref();
const form = reactive({
  title: "",
  priority: "",
  type: "",
  expectTime: "",
  content: "",
});
const rules = {
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  priority: [{ required: true, message: "请选择优先级", trigger: "change" }],
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
  expectTime: [
    { required: true, message: "请选择期望解决时间", trigger: "change" },
  ],
  content: [{ required: true, message: "请输入详细内容", trigger: "blur" }],
};

const editorRef = ref(null);
const editorConfig = {
  placeholder: "请输入问题详细描述，可插入图片、格式化文本等...",
  MENU_CONF: {
    uploadImage: {
      customUpload: async (file, insertFn) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          insertFn(e.target.result);
        };
        reader.readAsDataURL(file);
      },
    },
    // 完全禁用网络图片插入
    insertImage: {
      disabled: true,
    },
    // 完全禁用视频插入
    insertVideo: {
      disabled: true,
    },
    // 完全禁用视频上传
    uploadVideo: {
      disabled: true,
    },
  },
};
const toolbarConfig = {
  toolbarKeys: [
    "bold",
    "italic",
    "underline",
    "bulletedList",
    "numberedList",
    "undo",
    "redo",
    "uploadImage", // 只保留本地图片上传
  ],
};
function handleCustomPaste(editor, event) {
  const items = event.clipboardData && event.clipboardData.items;
  if (items) {
    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      if (item.type.indexOf("image") !== -1) {
        const file = item.getAsFile();
        const reader = new FileReader();
        reader.onload = (e) => {
          editor.insertNode({
            type: "image",
            src: e.target.result,
            alt: "",
            href: "",
            children: [{ text: "" }],
          });
        };
        reader.readAsDataURL(file);
        event.preventDefault();
        return false;
      }
    }
  }
  const text = event.clipboardData.getData("text/plain");
  if (text) {
    editor.insertText(text);
    event.preventDefault();
    return false;
  }
  return true;
}
const priorityMap = {
  low: "低",
  middle: "中",
  high: "高",
};
const typeMap = {
  bug: "问题",
  needs: "需求",
};
const statusMap = {
  pending: "待处理",
  fixed: "已解决",
  expired: "作废",
};

async function loadIssues() {
  try {
    const { data } = await fetchFeedbackList();
    issues.value = Array.isArray(data) ? data : [];
  } catch (e) {
    ElMessage.error("获取问题清单失败");
  }
}

function handleEditorCreated(editor) {
  editorRef.value = editor;
}

async function handleSubmit() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await createFeedback({
          title: form.title,
          priority: form.priority,
          type: form.type,
          expectTime: form.expectTime,
          content: form.content,
        });
        ElMessage.success("提交成功");
        resetForm();
        page.value = "list";
        await loadIssues();
      } catch (e) {
        ElMessage.error("提交失败");
      }
    }
  });
}

function resetForm() {
  form.title = "";
  form.priority = "";
  form.type = "";
  form.expectTime = "";
  form.content = "";
}

function priorityTagType(priority) {
  switch (priority) {
    case "high":
      return "danger";
    case "middle":
      return "warning";
    case "low":
      return "info";
    default:
      return "default";
  }
}
function statusTagType(status) {
  switch (status) {
    case "pending":
      return "warning";
    case "fixed":
      return "success";
    case "expired":
      return "danger";
    default:
      return "default";
  }
}
function startEditStatus(idx) {
  editingStatusRow.value = idx;
}
async function endEditStatus(row) {
  editingStatusRow.value = null;
  try {
    await updateFeedback(row.id, { status: row.status });
    ElMessage.success("状态已更新");
    await loadIssues();
  } catch (e) {
    ElMessage.error("状态更新失败");
  }
}
function filterStatus(value, row) {
  return row.status === value;
}
function formatDate(date) {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, "0");
  const d = String(date.getDate()).padStart(2, "0");
  const h = String(date.getHours()).padStart(2, "0");
  const min = String(date.getMinutes()).padStart(2, "0");
  return `${y}-${m}-${d} ${h}:${min}`;
}
function handleTabClick(tab) {
  if (tab.paneName === 'list') {
    loadIssues();
  }
}
function open() {
  visible.value = true;
  page.value = "form";
}
function close() {
  visible.value = false;
}
// 处理截图粘贴事件，富文本聚焦时自动插入图片
function handlePaste(imgSrc) {
  // 获取 wangeditor 的 API 实例
  const editor =
    editorRef.value && editorRef.value.isFocused()
      ? editorRef.value
      : null;
  if (editor) {
    editor.insertNode({
      type: "image",
      src: imgSrc,
      alt: "",
      href: "",
      children: [{ text: "" }],
    });
  }
}
defineExpose({ open, close, handlePaste });
</script>

<style scoped lang="scss">
.issue-drawer {
  .el-drawer__header {
    display: none;
  }
  .el-drawer__body {
    padding: 18px 18px 0 18px;
    background: #fafcff;
    min-height: 100vh;
    padding-bottom: 70px;
  }
}
.drawer-header {
  display: flex;
  align-items: center;
  height: 48px;
  padding: 0 0 12px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 8px;
  .drawer-title-bar {
    width: 4px;
    height: 22px;
    background: #409eff;
    border-radius: 2px;
    margin-right: 12px;
    flex-shrink: 0;
  }
  .drawer-title {
    font-size: 18px;
    font-weight: 600;
    color: #222;
    flex: 1;
  }
  .drawer-close {
    font-size: 20px;
    color: #909399;
    cursor: pointer;
    margin-left: 8px;
    transition: color 0.2s;
    &:hover {
      color: #409eff;
    }
  }
}
.issue-form-scroll {
  flex: 1 1 auto;
  overflow-y: auto;
  padding-right: 8px;
  padding-bottom: 80px;
}
.drawer-footer-bar {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 16px 18px;
  background: #fafcff;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  z-index: 10;
}
.drawer-tabs {
  margin-bottom: 12px;
}
.issue-list-section {
  margin-bottom: 24px;
}
.issue-content {
  max-height: 80px;
  overflow: auto;
}
.editor-wrapper {
  width: 100%;
  border: 1.5px solid #e0eaff;
  border-radius: 10px;
  padding: 6px;
  background: #fff;
  box-shadow: 0 2px 8px #b3d8ff22;
}
</style>
